package com.webcode.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.webcode.pojo.User;
import com.webcode.service.UserService;
import com.webcode.service.impl.UserServiceImpl;

/**
 * @ClassName RegistServlet.java
 * @Description TODO
 * @Author wushaopei
 * @Date 2020年9月19日
 * @Version 1.0
 */
public class RegistServlet extends HttpServlet{
	
	private static final long serialVersionUID = 1L;
	
	private UserService userService = new UserServiceImpl();

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 获取请求的参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String code = request.getParameter("code");
		
		// 写死验证码，为 6666 ,注意，验证兼容字母大小写
		if( "wsp6666".equalsIgnoreCase(code)){
			// 检查用户名是否可用
			if( userService.existsUsername(username)){
				// 用户名已存在，不可用
				System.out.println("用户名【" + username +"】已存在");
				// 消息回显
				request.setAttribute("msg", "用户名【" + username +"】已存在");
				request.setAttribute("username", username);
				request.setAttribute("email", email);
				// 转发以斜杠大头，这个斜杠表示 http://ip:port/工程名/映射到代码的 WebContent 目录
				request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
			}else{
				// 注册用户
				userService.regist(new User(null,username,password,email));
				// 转发以斜杠打头，这个斜杠表示 http://ip:port/工程名/映射到代码的 WebContent 目录
				request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request, response);
			}
		}else{
			System.out.println("验证码不正确： " + code);
			// 转发以斜杠打头，这个斜杠表示 http://ip:port/工程名/映射到代码的 WebContent 目录
			request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response);
		}
	}

}
